<template>
  <div class="card content-box" v-if="dataLoaded">
    <div class="post">
      <div class="postTitle">
        <div class="postTitle__text">{{ postDtl.postTitle }}</div>
        <div class="replyBtn" @click="_scrollToEditor">回复</div>
      </div>
      <div class="commentList">
        <div class="postItem">
          <div class="postType">帖</div>
          <div class="postItem__userInfo">
            <div class="userOwner"></div>
            <el-image class="userAvatar" :src="`${VITE_API_URL}/file/download/${postDtl.userHeadFileId}`"></el-image>
            <div class="userName">{{ postDtl.userName }}</div>
          </div>
          <div class="postItem__con">
            <div class="commentText"><span v-html="postDtl.postContent"></span></div>
            <div class="postItem__con__footer">
              <div class="createTime">{{ postDtl.createTime }}</div>
              <div class="commentReplyBtn" @click="_scrollToEditor">回复</div>
            </div>
          </div>
        </div>
        <div class="postItem" v-for="(item, index) in commentList" :key="item.postId">
          <div class="postItem__userInfo">
            <el-image class="userAvatar" :src="`${VITE_API_URL}/file/download/${item.userHeadFileId}`"></el-image>
            <div class="userName">{{ item.userName }}</div>
          </div>
          <div class="postItem__con">
            <div class="commentText"><span v-html="item.commentContent"></span></div>
            <div class="postItem__con__footer">
              <div class="floorNum">{{ `${item.floor}楼` }}</div>
              <div class="createTime">{{ item.createTime }}</div>
              <div class="commentReplyDelBtn" v-if="item.userId === userId" @click="_delComment(index)">删除</div>
              <div class="commentReplyBtn" @click="_replyCommnet(index)">{{ item.isCollapse ? "收起回复" : "回复" }}</div>
            </div>
            <div class="replyList" :style="{ 'max-height': item.replyListHei }">
              <div class="replyItemWrap">
                <div class="replyItem" v-for="(val, idx) in item.replyList" :key="val.replyId">
                  <div class="replyItem__con">
                    <el-image class="replyUserAvatar" :src="`${VITE_API_URL}/file/download/${val.userHeadFileId}`"></el-image>
                    <div class="replyInfo">
                      <span class="replyUserName">{{ val.userName }}</span>
                      <span class="replyCon">
                        {{ val.replyContent }}
                      </span>
                    </div>
                  </div>
                  <div class="replyItem__footer">
                    <span class="replyItem__footer__createTime">{{ val.createTime }}</span>
                    <span class="replyItem__footer__delBtn" v-if="val.userId === userId" @click="_delReply(index, idx)"
                      >删除</span
                    >
                    <span class="replyItem__footer__replyBtn" @click="_replyFloor(index, idx)">回复</span>
                  </div>
                </div>
                <div class="selfReplyBtn" v-if="item.replyList?.length">
                  <el-button plain type="text" size="small" @click="_selfReply(index)">我也说一句</el-button>
                </div>
                <el-input
                  type="textarea"
                  v-model="item.replyContent"
                  maxlength="2000"
                  show-word-limit
                  :ref="el => getTextRef(el, index)"
                ></el-input>
                <div class="submitReplyBtn"><el-button plain type="primary" @click="_submitReply(index)">发表</el-button></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-pagination layout="prev, pager, next" v-model:current-page="curPage" :total="total" v-if="commentList?.length" />
      <div class="postEdit">
        <div class="postEditTitle">发表回复</div>

        <WangEditor id="editor" v-model:value="commentContent" mode="simple" height="200px" />
        <el-button class="submitBtn" type="primary" @click="_submit">发表</el-button>
      </div>
    </div>

    <!-- <el-button type="primary" @click="dialogVisible = true"> 内容预览 </el-button> -->
    <el-dialog v-model="dialogVisible" title="富文本内容预览" width="1300px" top="50px">
      <div class="view" v-html="commentContent"></div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="wangEditor">
import { computed, onMounted, ref, watch } from "vue";
import { useRoute } from "vue-router";
import WangEditor from "@/components/WangEditor/index.vue";
import { VITE_API_URL } from "@/config/index";
import {
  getPostDtl,
  getCommentList,
  sendComment,
  getReplyList,
  sendReply,
  deleteComment,
  deleteReply
} from "@/api/modules/forum";
import { ResultData } from "@/api/interface";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/modules/user";

const userStore = useUserStore();

const route = useRoute();
const dataLoaded = ref(false);
const postDtl: any = ref({});
const commentList: any = ref([]);
const commentContent = ref("");
const curPage = ref(1);
const total = ref(0);
const dialogVisible = ref(false);
const textRefList: any = ref([]);
const userId = computed(() => userStore.userInfo.userId);

/**
 * 滚动到编辑器
 */
const _scrollToEditor = () => {
  document.getElementById("editor")!.scrollIntoView();
};

/**
 * 回复楼友
 */
const _replyFloor = (index: number, idx: number) => {
  const curComment = commentList.value[index];
  textRefList.value[index].focus();
  curComment.replyContent = `回复 ${curComment.replyList[idx].userName} `;
};
/**
 * 回复评论
 */
const _selfReply = (index: number) => {
  const curComment = commentList.value[index];
  textRefList.value[index].focus();
  curComment.replyContent = "";
};

/**
 * 折叠/展开回复评论
 */
const _replyCommnet = async (index: number) => {
  const curComment = commentList.value[index];
  if (!curComment.canClick) return false;
  curComment.isCollapse = !curComment.isCollapse;
  // curComment.canClick = false;

  curComment.isCollapse && textRefList.value[index].focus();

  if (curComment.isCollapse) {
    try {
      const res = await getReplyList({ commentId: curComment.commentId });
      curComment.replyList = res.dataList;
      curComment.replyListHei = "1000px";
    } catch (error) {
      console.log(error);
    }
  } else {
    curComment.replyListHei = "0";
    setTimeout(() => {
      curComment.replyList = [];
    }, 500);
  }

  setTimeout(() => {
    curComment.canClick = true;
  }, 500);
};

/**
 * 删除评论
 */
const _delComment = (index: number) => {
  const curComment = commentList.value[index];
  deleteComment({ commentId: curComment.commentId }).then(() => {
    getCommentData();
  });
};

/**
 * 删除回复
 */
const _delReply = async (index: number, idx: number) => {
  const curComment = commentList.value[index];

  deleteReply({ replyId: curComment.replyList[idx].replyId }).then(async () => {
    try {
      const res = await getReplyList({ commentId: curComment.commentId });
      curComment.replyList = res.dataList;
    } catch (error) {}
  });
};

/**
 * 提交回复
 */
const _submitReply = (index: number) => {
  const curComment = commentList.value[index];
  if (!curComment.replyContent) {
    ElMessage.error("回复内容不能为空");
    return false;
  }

  sendReply({ commentId: curComment.commentId as string, replyContent: curComment.replyContent }).then(async () => {
    try {
      const res = await getReplyList({ commentId: curComment.commentId });
      curComment.replyList = res.dataList;
      curComment.replyContent = "";
    } catch (error) {}
  });
};

/**
 * 提交新帖
 */
const _submit = () => {
  if (!commentContent.value) {
    ElMessage.error("回复内容不能为空");
    return false;
  }
  sendComment({ postId: route.params.postId as string, commentContent: commentContent.value }).then(() => {
    getCommentData();
    commentContent.value = "";
  });
};

/**
 * 获取回复ref集合
 */
const getTextRef = (el: any, index: number) => {
  if (el) {
    textRefList.value[index] = el;
  }
};

/**
 * 获取帖子列表
 */
const getCommentData = async () => {
  dataLoaded.value = false;
  try {
    const { result } = (await getCommentList({
      pageNum: curPage.value,
      pageSize: 10,
      postId: route.params.postId as string
    })) as ResultData;
    commentList.value = result.dataList;
    commentList.value.forEach((item: any) => {
      getReplyList({ commentId: item.commentId }).then(res => {
        item.replyList = res.dataList;
        item.isCollapse = item.replyList.length ? true : false;
        item.replyListHei = item.replyList.length ? "1000px" : 0;
        item.canClick = true;
        item.replyContent = "";
      });
    });

    total.value = result.total;
    dataLoaded.value = true;
  } catch (error) {}
};

watch(
  () => curPage.value,
  () => {
    getCommentData();
  }
);
onMounted(async () => {
  try {
    const { result } = (await getPostDtl({ postId: route.params.postId as string })) as ResultData;
    postDtl.value = result;
    getCommentData();
  } catch (error) {}
});
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
